//
//  CounterItemView.swift
//  SCA
//
//  Created by tjun on 2025/9/16.
//

import UIKit
import SnapKit

class ComputingPowerTypeView: UIView {
    
    private let typeLabel = UILabel(font: UIFontMediumMake(16), textColor: .white)
    private let amountLabel = UILabel(font: UIFontSemiboldMake(16), textColor: UIColorMake(0x0062FE))
    private let countLabel = UILabel(font: UIFontSemiboldMake(14), textColor: UIColor.white, textAlignment: .center)

    let gradientView = GradientView()
    let minusButton = UIButton(type: .system)
    let plusButton = UIButton(type: .system)
    var model: BuyPowerOptionModel? {
        didSet {
            guard let model = model else { return }
            typeLabel.text = model.title
            amountLabel.text = model.investDisp
            
        }
    }
    
    var onMinusButtonTapped: ((Int) -> Void)?
    var onPlusButtonTapped: ((Int) -> Void)?
    
    var count: Int = 0 {
        didSet { updateUI() }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        gradientView.addTo(self)
        gradientView.colors = [UIColorMake(0x05D4FC), UIColorMake(0xBE0DEF), UIColorMake(0xF202D3)]
        gradientView.locations = [0, 0.5, 1]
        gradientView.setStartPoint(CGPoint(x: 0, y: 0.5), endPoint: CGPointMake(1, 0.5))
        gradientView.isGradientBorder = true
        gradientView.cornerRadius = AppStyle.cornerRadius.normal
        gradientView.borderWidth = 1
        gradientView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        typeLabel.addTo(self)
        typeLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
        }
        
        amountLabel.addTo(self)
        amountLabel.snp.makeConstraints { make in
            make.left.equalTo(typeLabel.snp.right).offset(16)
            make.centerY.equalToSuperview()
        }
        
        // Plus button
        plusButton.addTo(self)
        plusButton.setTitle("＋", for: .normal)
        plusButton.titleLabel?.font = .boldSystemFont(ofSize: 18)
        plusButton.setTitleColor(UIColorMake(0x0062FE), for: .normal)
        plusButton.addCorner(radius: 5)
        plusButton.backgroundColor = UIColorMake(0xE7E7E7).withAlphaComponent(0.2)
        plusButton.addTarget(self, action: #selector(plusButtonTapped), for: .touchUpInside)
        plusButton.snp.makeConstraints { make in
            make.right.equalTo(-12)
            make.width.height.equalTo(22)
            make.centerY.equalToSuperview()
        }

        countLabel.text = "0"
        countLabel.addTo(self)
        countLabel.snp.makeConstraints { make in
            make.right.equalTo(plusButton.snp.left)
            make.width.greaterThanOrEqualTo(30)
            make.centerY.equalToSuperview()
        }
        
        minusButton.addTo(self)
        minusButton.setTitle("－", for: .normal)
        minusButton.titleLabel?.font = .boldSystemFont(ofSize: 18)
        minusButton.setTitleColor(UIColorMake(0x0062FE), for: .normal)
        minusButton.addCorner(radius: 5)
        minusButton.backgroundColor = UIColorMake(0xE7E7E7).withAlphaComponent(0.2)
        minusButton.addTarget(self, action: #selector(minusButtonTapped), for: .touchUpInside)
        minusButton.snp.makeConstraints { make in
            make.right.equalTo(countLabel.snp.left)
            make.width.height.centerY.equalTo(plusButton)
        }
        
        updateUI()
    }
    
    private func updateUI() {
        countLabel.text = "\(count)"
        isHighlighted = count > 0
        
        if count == 0 {
            minusButton.alpha = 0.5
            minusButton.isUserInteractionEnabled = false
        } else {
            minusButton.alpha = 1
            minusButton.isUserInteractionEnabled = true
        }
        
        guard let model = model else { return }
 
        if count >= model.max {
            plusButton.alpha = 0.5
            plusButton.isUserInteractionEnabled = false
        } else {
            plusButton.alpha = 1
            plusButton.isUserInteractionEnabled = true
        }
    }

    @objc private func minusButtonTapped() {
        if count > 0 {
            count -= 1
        }
        
        onMinusButtonTapped?(count)
    }
    
    @objc private func plusButtonTapped() {
        count += 1
        
        onPlusButtonTapped?(count)
    }
    
    var isHighlighted: Bool = false {
        didSet {
            if isHighlighted {
                UIView.animate(withDuration: 0.25) {
                    self.gradientView.colors = [UIColorMake(0x05D4FC), UIColorMake(0xBE0DEF), UIColorMake(0xF202D3)]
                }
            } else {
                UIView.animate(withDuration: 0.25) {
                    self.gradientView.colors = [UIColorMake(0xC5C5C5), UIColorMake(0xC5C5C5), UIColorMake(0xC5C5C5)]
                }
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}



class CounterItemView: UIView {
    
    private let titleLabel = UILabel()
    private let priceLabel = UILabel()
    private let minusButton = UIButton(type: .system)
    private let plusButton = UIButton(type: .system)
    private let countLabel = UILabel()
    
    private var gradientLayer: CAGradientLayer?
    
    /// 当前数量
    var count: Int = 0 {
        didSet { updateUI() }
    }
    
    /// 渐变边框颜色，默认粉紫
    var gradientColors: [UIColor] = [UIColor.systemPink, UIColor.systemPurple] {
        didSet { updateUI() }
    }
    
    init(title: String, price: String) {
        super.init(frame: .zero)
        setupUI(title: title, price: price)
        updateUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(title: String, price: String) {
        layer.cornerRadius = 8
        layer.masksToBounds = true
        backgroundColor = UIColor.black.withAlphaComponent(0.2)
        
        // Title
        titleLabel.text = title
        titleLabel.textColor = .white
        titleLabel.font = .systemFont(ofSize: 16)
        
        // Price
        priceLabel.text = price
        priceLabel.textColor = UIColor.systemBlue
        priceLabel.font = .boldSystemFont(ofSize: 16)
        
        // Minus button
        minusButton.setTitle("－", for: .normal)
        minusButton.titleLabel?.font = .boldSystemFont(ofSize: 20)
        minusButton.tintColor = .white
        minusButton.addTarget(self, action: #selector(didTapMinus), for: .touchUpInside)
        
        // Plus button
        plusButton.setTitle("＋", for: .normal)
        plusButton.titleLabel?.font = .boldSystemFont(ofSize: 20)
        plusButton.tintColor = .white
        plusButton.addTarget(self, action: #selector(didTapPlus), for: .touchUpInside)
        
        // Count label
        countLabel.text = "0"
        countLabel.textColor = .white
        countLabel.font = .boldSystemFont(ofSize: 16)
        countLabel.textAlignment = .center
        
        // 布局
        addSubview(titleLabel)
        addSubview(priceLabel)
        addSubview(minusButton)
        addSubview(countLabel)
        addSubview(plusButton)
        
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12)
            make.centerY.equalToSuperview()
        }
        
        priceLabel.snp.makeConstraints { make in
            make.leading.equalTo(titleLabel.snp.trailing).offset(8)
            make.centerY.equalToSuperview()
        }
        
        plusButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().inset(12)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(30)
        }
        
        countLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalTo(plusButton.snp.leading).offset(-8)
            make.width.equalTo(24)
        }
        
        minusButton.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalTo(countLabel.snp.leading).offset(-8)
            make.width.height.equalTo(30)
        }
        
        // 默认边框
        layer.borderColor = UIColor.darkGray.cgColor
        layer.borderWidth = 1
    }
    
    private func updateUI() {
        countLabel.text = "\(count)"
        
        if count > 0 {
            // 渐变边框
            if gradientLayer == nil {
                let gradient = CAGradientLayer()
                gradient.startPoint = CGPoint(x: 0, y: 0.5)
                gradient.endPoint = CGPoint(x: 1, y: 0.5)
                gradient.frame = bounds
                gradient.cornerRadius = 8
                gradient.colors = gradientColors.map { $0.cgColor }
                
                let shape = CAShapeLayer()
                shape.path = UIBezierPath(roundedRect: bounds, cornerRadius: 8).cgPath
                shape.lineWidth = 2
                shape.fillColor = UIColor.clear.cgColor
                shape.strokeColor = UIColor.black.cgColor
                gradient.mask = shape
                
                layer.addSublayer(gradient)
                gradientLayer = gradient
            } else {
                gradientLayer?.colors = gradientColors.map { $0.cgColor }
                gradientLayer?.frame = bounds
            }
            
            minusButton.alpha = 1.0
            minusButton.isEnabled = true
        } else {
            // 移除渐变
            gradientLayer?.removeFromSuperlayer()
            gradientLayer = nil
            
            layer.borderColor = UIColor.darkGray.cgColor
            layer.borderWidth = 1
            
            minusButton.alpha = 0.4
            minusButton.isEnabled = false
        }
    }
    
    @objc private func didTapMinus() {
        if count > 0 {
            count -= 1
        }
    }
    
    @objc private func didTapPlus() {
        count += 1
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer?.frame = bounds
        if let shape = gradientLayer?.mask as? CAShapeLayer {
            shape.path = UIBezierPath(roundedRect: bounds, cornerRadius: 8).cgPath
        }
    }
}
